<!-- 推广中心 -->
<template>
	<view class="container">
		<view v-if="NO_SHOW_MEMBER.includes(_getConfig('_APP_ENV'))">
			<view class="content">
				<!-- 修改组件标签为导入时的名称 -->
				<ImageLoad filePath="plugbg.png" class="img-bg" /> <!-- 修改为自闭合标签 -->

				<view class="toBack" @click="$router.push('/')">
					<svg-load name="back" class="back" />
					<view class="code_box">
						<p class="code1 fw-bold">{{ _t18('plug_invite') }}</p>
						<p class="code2">{{ _t18('plug_toInvite') }}</p>
						<view class="erweima">
							<QRCode :address="sharkCode"></QRCode>
						</view>
						<view class="sharkCode">
							<Copy :data="sharkCode">
								<template #copyMsg>
									<!-- 邀请码 -->
									<p class="ff-num">{{ _t18('plug_shareCode') }}: {{ sharkCode }}</p>
								</template>
							</Copy>
						</view>
						<view class="shareLink">
							<p class="ff-num">{{ _t18('plug_shareLink') }}：</p>
							<Copy :data="`${shareLink}${sharkCode}`">
								<template #copyMsg>
									<!-- 推广链接 -->
									<p class="ff-num link">{{ shareLink }}{{ sharkCode }}</p>
								</template>
							</Copy>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-else>
			<!-- 修改 HeaderBar 组件 -->
			<HeaderBar :currentName="_t18('plug')" :cuttentRight="cuttentRight" :border_bottom="false"
				@showPopup="showPopup" /> <!-- 改为自闭合 -->

			<!-- 修改 Popup 组件 -->
			<Popup :show="showRule" @handelClose="closePopup" :content="popupContent" :direction="direction" />
			<!-- 改为自闭合 -->

			<!-- 团队信息 -->
			<view class="banner">
				<view :class="__theme == 'dark' ? 'plugbg' : 'plug_bg'">
					<view class="shareContent">
						<!-- 邀请好友一起赚币 -->
						<p class="shareContent_title fw-bold">{{ _t18('plug_invite', ['aams']) }}</p>
						<!-- 邀请好友，充值即刻获取佣金 -->
						<p class="shareContent_info">{{ _t18('plug_toInvite') }}</p>
						<view class="sharkCode">
							<Copy :data="sharkCode" :contentFix="'start'" :fontSize="'12px'">
								<template #copyMsg>
									<!-- 邀请码 -->
									<p class="ff-num">{{ _t18('plug_shareCode') }}：{{ sharkCode }}</p>
								</template>
							</Copy>
						</view>
						<view class="shareLink" :contentFix="'start'">
							<Copy :data="`${shareLink}${sharkCode}`" :fontSize="'12px'">
								<template #copyMsg>
									<!-- 推广链接 -->
									<p class="ff-num">{{ _t18('plug_shareLink') }}：{{ shareLink }}{{ sharkCode }}</p>
								</template>
							</Copy>

							<view class="jin" @click="ewei">
								专属二维码
							</view>
						</view>
					</view>
				</view>
				<view v-if="!['das'].includes(_getConfig('_APP_ENV'))">
					<view class="teamInfo">

						<view>
							<p>直推人数</p>
							<span class="fw-num">{{ teamInfo.sumCount || 0 }}</span>
						</view>
						<!-- 佣金金额 -->
						<view>
							<p>{{ _t18('plug_amount1', ['aams']) }}</p>
							<span class="ff-num">{{ teamInfo.sumYeji || 0 }}&nbsp;WETH</span>
						</view>
						<view></view>
					</view>
				</view>
			</view>
			<view v-if="!['das'].includes(_getConfig('_APP_ENV'))">
				<!-- 我的推广 -->
				<view class="promotion_my" v-if="!['bitfly'].includes(_getConfig('_APP_ENV'))">
					<view class="title fw-bold">{{ _t18('plug_myShare', ['aams']) }}</view>
					<Tab :tabList="tabList" :active="curIndex" @change="changeIndex" :lineWidth="0"
						:flexBetween="false">
						<!-- 加载中动画 -->
						<template #tabContent>
							<view class="header">
								<!--用户ID  返佣金额  注册时间 -->
								<p>{{ _t18('plug_userId') }}</p>
								<p>{{ _t18('plug_performance_amount') }}</p>
								<p>{{ _t18('plug_registerTime') }}</p>
							</view>

							<van-loading v-if="showLoading" />
							<Nodata v-if="teamList.length <= 0 && !showLoading"></Nodata>
							<view v-else class="contentBox">
								<view class="content1" v-for="(item, index) in teamList" :key="index">
									<p class="ff-num">{{ item.userId || '' }}</p>
									<p class="ff-num">{{ item.yejiAmount}}&nbsp;WETH</p>
									<!-- <p>{{ item.createTime?_timeFormat(item.createTime, 'HH:mm MM/DD', true):'' }}</p> -->
									<p class="ff-num">
										{{ item.createTime }}
									</p>
								</view>
							</view>
						</template>

					</Tab>
					<view v-if="show" class="image-modal">
						<!-- 遮罩层 -->
						<view class="modal-overlay" @click="show = false"></view>

						<!-- 图片内容 -->
						<view class="modal-content" @touchstart="handleTouchStart" @touchend="handleTouchEnd"
							id="html-canvas">
							<view style="position:absolute;bottom: 25px;right: 25px;">
								<QRCode :address="shareLink + sharkCode "></QRCode>
							</view>
							<img src="https://s2023.oss-cn-qingdao.aliyuncs.com/echo2.0672099e8508c49eeb167fda05762c69b.jpg"
								style="width: 100%;" alt="">
						</view>
						<view class="saveBtn" @click="downloadImg">{{ _t18('Bank_save') }}</view>
					</view>
				</view>

			</view>

			<!-- 质押挖矿规则弹窗 -->
			<Popup :show="showRule" @handelClose="closePopup" :content="popupContent" :direction="direction">
			</Popup>
		</view>
	</view>
</template>

<script setup>
	import {
		NO_SHOW_MEMBER
	} from '@/config/index'
	import {
		_t18
	} from '@/utils/public'
	import HeaderBar from '@/components/HeaderBar/index.vue'
	import QRCode from '@/components/common/QRCode/index.vue'
	import Copy from '@/components/common/Copy/index.vue'
	import Tab from '@/components/Tab/index.vue'
	import Popup from '@/components/Popup/index.vue'
	import {
		useUserStore
	} from '@/store/user/index'
	import {
		getAgentInfo,
		getAgentList
	} from '@/api/plug.js'
	import {
		onMounted,
		computed
	} from 'vue'
	import {
		rulesList
	} from '@/api/common/index'
	import html2canvas from "html2canvas";
	// 假设 image-load 组件路径，根据实际情况修改
	import ImageLoad from '@/components/common/ImageLoad/index.vue'
	import {
		ref
	} from 'vue'

	const cuttentRight = {
		iconRight: [{
			iconName: 'guize',
			clickTo: ''
		}]
	}
	const useStore = useUserStore()
	const userInfo = useStore.userInfo

	// 安全的邀请码获取
	const sharkCode = computed(() => {
		return userInfo?.user?.activeCode || ''
	})

	// const shareLink = `${import.meta.env.VITE_APP_PLANFORM_H5}/#/i&`
	const shareLink = `${location.origin}/#/i&`
	// 推广中心数据
	const showLoading = ref(true)
	const teamInfo = ref({})
	const teamList = ref([])
	const popupContent = ref({})
	const getTeamInfo = async () => {
		const res = await getAgentInfo()
		if ((res.code === 200)) {
			teamInfo.value = res.data
		}
	}
	const getTeamList = async () => {
		showLoading.value = true
		const res = await getAgentList({
			params: {
				leve: curIndex.value + 1
			}
		})
		console.log(typeof res.code, res.code, 'res.code')

		if (res.code === 200) {
			showLoading.value = false
			teamList.value = res.data

		} else {
			// 如果请求失败，也要关闭加载状态
			showLoading.value = false
		}
	}
	const getPopupContent = async () => {
		const res = await rulesList('PROMOTION_CENTER_EXPLAIN')
		if ((res.code === '200')) {
			popupContent.value = res.data
		}
	}
	onMounted(() => {
		getTeamInfo()
		getTeamList()
		getPopupContent()
	})
	// const teamInfo = computed(() => {
	//   let obj = {}
	//   obj = { one: 10, two: 20, three: 30, sum: '60', amount: 10000000 }
	//   return obj
	// })
	const showRule = ref(false)
	const show = ref(false)
	const txt = _t18('plug_rule') //规则
	const direction = ref('bottom')
	let showPopup = () => {
		showRule.value = true
	}
	let closePopup = () => {
		showRule.value = false
	}
	let closePopup1 = () => {
		show.value = false
	}

	const manual = computed(() => {
		let list = []
		list = [{
				title: '推广规则',
				content: [{
					childContent: '如果用户使用了您的邀请码注册，即为您的下级。这个用户再次的邀请用户，即为您的二级下级。 of Stake，即权益证明）机制产生的奖励。在这个机制中，用户将数字资产委托给节点，节点在区块链上行使出块、打包交易等权利并获得奖励。用户根据锁仓数量按比例分享节点获得的奖励。'
				}]
			},
			{
				title: '推广奖励',
				content: [{
						childContent: '如果用户使用了您的邀请码注册，即为您的下级。这个用户再次的邀请用户，即为您的二级下级。'
					},
					{
						childTitle: '1.下级充值奖励。',
						childContent: '您的下级进行充值，您即可获得他充值金额的1%作为奖励。'
					},
					{
						childTitle: '2.下级挖矿奖励。',
						childContent: '您的下级，如果进行了锁仓挖矿。那么你也可以获得对应的收益。'
					}
				]
			},
			{
				title: '例：A-B-C-D-E..',
				content: [{
						childContent: 'A可以获得B收益的3%'
					},
					{
						childContent: 'A可以获得C收益的2%'
					},
					{
						childContent: 'A可以获得D收益的1%'
					},
					{
						childContent: 'B可以获得C收益的3%'
					},
					{
						childContent: 'B可以获得D收益的2%'
					},
					{
						childContent: 'B可以获得E收益的1%'
					}
				]
			}
		]
		return list
	})
	const curIndex = ref(0)
	const tabList = computed(() => {
		let list = []
		// list = ['一代', '二代', '三代']
		list = [_t18('', ['aams']), _t18('', ['aams']), _t18('', ['aams'])]
		return list
	})
	const changeIndex = (v) => {
		curIndex.value = v
		teamList.value = []
		getTeamList()
	}
	const longPressTimer = ref(null); // 用于记录长按的定时器
	const longPressDuration = ref(500); // 长按的时长阈值（单位：毫秒）

	// 长按开始
	const handleTouchStart = () => {
		// 设置定时器，如果在指定时间内没有触发 touchend，则认为是长按
		longPressTimer.value = setTimeout(() => {
			downloadImg();
		}, longPressDuration.value);
	};

	// 长按结束
	const handleTouchEnd = () => {
		// 清除定时器，防止误触发
		if (longPressTimer.value) {
			clearTimeout(longPressTimer.value);
			longPressTimer.value = null; // 重置定时器
		}
	};
	// 生成并下载
	const downloadImg = () => {
		const divDom = document.getElementById('html-canvas')
		html2canvas(divDom, {
			backgroundColor: null,
			useCORS: true
		}).then((canvas) => {
			const base64Img = canvas.toDataURL('image/png')

			if (window.plus) {
				// 检查权限
				plus.android.requestPermissions(
					['android.permission.WRITE_EXTERNAL_STORAGE'],
					function(result) {
						if (result.granted.length > 0) {
							saveImageToGallery(base64Img)
						} else {
							plus.nativeUI.confirm(
								'需要存储权限才能保存图片，是否前往设置？',
								function(e) {
									if (e.index === 0) {
										// 跳转应用设置页面
										if (plus.os.name.toLowerCase() === 'android') {
											const main = plus.android.runtimeMainActivity()
											const Intent = plus.android.importClass(
												'android.content.Intent')
											const Settings = plus.android.importClass(
												'android.provider.Settings')
											const Uri = plus.android.importClass('android.net.Uri')
											const intent = new Intent()
											intent.setAction(Settings
												.ACTION_APPLICATION_DETAILS_SETTINGS)
											intent.setData(Uri.fromParts('package', main
												.getPackageName(), null))
											main.startActivity(intent)
										} else {
											// iOS
											plus.runtime.openURL('app-settings:')
										}
									}
								}, {
									title: '提示',
									buttons: ['去设置', '取消']
								}
							)
						}
					},
					function(error) {
						alert('获取权限失败')
						plus.nativeUI.toast('获取权限失败')
					}
				)
			} else {
				// 浏览器环境
				let a = document.createElement('a')
				a.href = base64Img
				a.download = `${+new Date()}.png`
				a.click()
			}
		})
	}

	// 保存图片到相册
	// 保存图片到相册
	const saveImageToGallery = (base64Img) => {
		try {
			// 去掉 base64 前缀
			const base64Data = base64Img.split(',')[1]
			// 获取应用私有文档目录
			const dirPath = plus.io.convertLocalFileSystemURL('_doc')
			const fileName = `${Date.now()}.png`
			const filePath = `${dirPath}/${fileName}`

			// 写入文件
			const bitmap = new plus.nativeObj.Bitmap()
			bitmap.loadBase64Data(base64Img, () => {
				bitmap.save(filePath, {}, () => {
					// 保存图片到相册
					plus.gallery.save(filePath, () => {
						plus.nativeUI.toast('保存成功')
						// 清理临时文件
						bitmap.clear()
					}, (e) => {
						plus.nativeUI.toast('保存失败')
						bitmap.clear()
					})
				}, (e) => {
					plus.nativeUI.toast('图片处理失败')
					bitmap.clear()
				})
			}, (e) => {
				plus.nativeUI.toast('图片加载失败')
			})
		} catch (e) {
			plus.nativeUI.toast('保存失败')
			console.error(e)
		}
	}
	const ewei = () => {
		show.value = true
	}
</script>

<style lang="scss" scoped>
	* {
		color: var(--ex-default-font-color);
		font-size: 14px;
	}

	.container {
		// padding: 15px;
		display: flex;
		flex-direction: column;

		// gap: 15px;
		header {
			padding-left: 0;
		}
	}

	.content {
		display: flex;
		font-size: 0;
		min-height: 100vh;
		padding: 15px;
		position: relative;

		.img-bg {
			position: absolute;
			top: 0;
			left: 0;
			height: 100%;
			width: 100%;
			object-fit: cover;
		}

		.toBack {
			position: absolute;
			margin-top: 30px;
			margin-left: 20px;

			.back {
				font-size: 18px;
			}
		}

		.code_box {
			min-width: 300px;
			position: fixed;
			top: 100px;
			left: 50%;
			transform: translate(-50%, 0);
			padding: 20px;
			background-color: #fff;
			border-radius: 10px;

			p.code1 {
				font-size: 18px;
				text-align: center;
			}

			p.code2 {
				font-size: 12px;
				text-align: center;
				color: #b5b5b5;
				margin-top: 10px;
			}

			.erweima {
				p {
					margin-top: -25px;
					font-size: 20px;
					text-align: center;
					font-weight: bold;
				}
			}

			.link {
				word-break: break-all;
			}
		}
	}

	.box .erweima {
		border: none;
	}

	.banner {
		padding:15px;
		display:block;
		.plug_bg {
			// background: url('https://s2023.oss-cn-qingdao.aliyuncs.com/resource/images/dark/plugbg.png') no-repeat center;
			// background-size: cover;
			padding: 45px 15px 20px;
			// z-index: 100000;

			.shareContent {
				width: 60%;

				.shareContent_title {
					font-size: 20px;
					color: var(--ex-font-color8);
				}

				.shareContent_info {
					font-size: 14px;
					color: var(--ex-font-color8);
					padding: 10px 0 30px;
				}

				.sharkCode,
				.shareLink {
					p {
						line-height: 1.2;
						font-size: 12px;
						word-break: break-all;
						color: var(--ex-font-color8);
						// word-wrap:break-word;
						// word-break:normal;
					}
				}
			}
		}

		.plugbg {
			background: url('https://s2023.oss-cn-qingdao.aliyuncs.com/resource/images/dark/plugbg.png') no-repeat center;
			background-size: cover;
			padding: 45px 15px 20px;

			.shareContent {
				width: 60%;

				.shareContent_title {
					font-size: 20px;
					color: var(--ex-font-color6);
				}

				.shareContent_info {
					font-size: 14px;

					padding: 10px 0 30px;
				}

				.sharkCode,
				.shareLink {
					p {
						line-height: 1.2;
						font-size: 12px;
						word-break: break-all;
						// word-wrap:break-word;
						// word-break:normal;
					}
				}
			}
		}

		img {
			width: 100%;
			height: auto;
		}

		.teamInfo {
			padding: 15px 0 0;
			display: flex;
			flex-wrap: wrap;
			width: 100%;
			flex-direction: row;
			align-items: center;
			justify-content: space-around;

			&>view {
				width: 50%;
				text-align: center;
			}

			// & > div {
			//   width: 33.33%;
			//   padding: 15px 5px;
			//   text-align: center;
			//   // flex: 1;
			//   p {
			//     height: 30px;
			//     color: var(--ex-passive-font-color);
			//     margin-bottom: 15px;
			//     word-wrap: break-word;
			//   }

			//   span {
			//     font-size: 16px;
			//     font-weight: 500;
			//   }
			// }
		}
	}

	.ff-num {
		white-space: nowrap;
	}

	.promotion_my {
		padding:15px;
		display:block;

		.title {
			// padding: 25px 15px 0 20px;
			color: var(--ex-font-color6);
			font-weight: bold;
			font-size: 16px;
			margin-top: 15px;
			display: block;
		}

		.header {
			padding: 15px 10px;
			display: flex;

			&>p:first-child {
				text-align: left;
			}

			&>p:last-child {
				text-align: right;
			}

			p {
				font-size: 12px;
				flex: 1;
				color: var(--ex-passive-font-color);
				text-align: center;
			}
		}

		.contentBox {
			height: 50vh;
			overflow: auto;
		}

		.content1 {
			padding: 15px 0;
			display: flex;

			&>p:first-child {
				text-align: left;
			}

			&>p:last-child {
				text-align: right;
			}

			p {
				padding: 0 15px;
				font-size: 12px;
				flex: 1;
				text-align: center;
				font-weight: 400;
			}
		}
	}

	.van-loading {
		text-align: center;
		padding: 30px;
	}

	:deep(.van-tab) {
		color: var(--ex-home-list-ftcolor) !important;
	}

	:deep(.van-tab--active) {
		color: var(--ex-home-list-ftcolor3) !important;
	}

	.jin {
		color: #fff;
		background: #03bc6f;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10px;
		border-radius: 18px;
		font-weight: bold;
		margin-top: 10%;
	}
</style>
<style>
	/* 遮罩层样式 */
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		/* 半透明黑色 */
		z-index: 1000;
	}

	.image-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		z-index: 99;
	}

	/* 图片内容样式 */
	.modal-content {
		position: absolute;
		top: 50%;
		left: 0;
		transform: translate(0%, -52%);
		padding: 0.533333rem;
		border-radius: 0.213333rem;
		z-index: 1001;
		text-align: center;
	}

	.saveBtn {
		width: 200px;
		height: 40px;
		position: absolute;
		bottom: 2vh;
		z-index: 10000;
		background: #ffffff;
		text-align: center;
		line-height: 40px;
		border-radius: 20px;
		left: 0;
		right: 0;
		margin: auto;
		font-size: 0.36rem;
		color: #000000;
	}

	.modal-content button {
		margin-top: 10px;
		padding: 5px 10px;
		background-color: #ff5722;
		color: white;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	.modal-content button:hover {
		background-color: #e040fb;
	}
</style>